package com.qiandian.android.base.net.http;

import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.util.Log;

import com.qiandian.android.base.ActivityRecords;
import com.qiandian.android.base.common.bean.BaseBean;
import com.qiandian.android.base.common.bean.CommonBean;
import com.qiandian.android.base.common.utils.JsonUtils;

import java.io.IOException;
import java.lang.reflect.Type;

import cn.tjad.tjad2.application.TjadApplication;
import cn.tjad.tjad2.route.PageId;
import cn.tjad.tjad2.utils.RouteUtils;
import cn.tjad.tjad2.utils.Tools;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by yanghongbing on 17/10/18.
 */

public class HttpListenerImpl implements Callback {

    private IDataCallBack callBack;

    private Handler handler;

    private Class<?> resultBean;

    private Type rawType = CommonBean.class;

    public HttpListenerImpl(@Nullable IDataCallBack callBack) {
        this.callBack = callBack;
        handler = new Handler(Looper.getMainLooper());
    }

    public void setResultBean(Class<?> resultBean) {
        this.resultBean = resultBean;
    }

    public void setRawType(Type rawType) {
        this.rawType = rawType;
    }

    @Override
    public void onFailure(Call call, final IOException e) {
        final HttpRequest request = (HttpRequest) call.request().tag();
        Log.d(HttpConstants.TAG, "--------onFailure " + request.getHttpId() + "--------");
        Log.d(HttpConstants.TAG,  "" + e.getMessage());
        Log.d(HttpConstants.TAG,  "--------request " + request.getHttpId() + " end--------");
        handler.post(new Runnable() {
            @Override
            public void run() {
                boolean consumed = false;
                if (callBack != null) {
                    consumed = callBack.onReceiveError(request.getHttpId(), -1, e.getMessage());
                }
                if (!consumed) {
                    //统一处理错误请求
//                    TJUtils.showToast("http " + request.getHttpId() + " " + e.getMessage());
                }
            }
        });
    }

    @Override
    public void onResponse(Call call, Response okResponse) throws IOException {
        Request okRequest = okResponse.request();
        final HttpRequest request = (HttpRequest) okRequest.tag();
        ResponseBody body = okResponse.body();
        final int responseCode = okResponse.code();
        String responseString = null;
        if (body != null) {
            responseString = body.string();
        }
        Log.d(HttpConstants.TAG, "--------onResponse " + request.getHttpId() + "--------");
        Log.d(HttpConstants.TAG, "response Code: " + okResponse.code());
        Log.d(HttpConstants.TAG, "response info : \n" + responseString);
        Log.d(HttpConstants.TAG,  "--------request " + request.getHttpId() + " end--------");
        final String finalResponseString = responseString;
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (responseCode == 200) {
                    BaseBean bean =  JsonUtils.parseObject(finalResponseString, resultBean, rawType);
                    if (bean != null) {
                        if (callBack != null) {
                            callBack.onDataRefresh(request.getHttpId(), bean);
                        }
                    } else {
                        Log.d(HttpConstants.TAG, "json parse failed: " + request.getHttpId() + ", " + finalResponseString);
                    }
                } else if (responseCode == 401) {
                    Tools.showToast("登录过期, 请重新登录");
                    ActivityRecords activityRecords = TjadApplication.getInstance().getActivityRecords();
                    RouteUtils.toPage(activityRecords.getTopActivity(), PageId.LOGIN, null);
                    activityRecords.finishAll();
                } else {
                    boolean consumed = false;
                    if (callBack != null) {
                        consumed = callBack.onReceiveError(request.getHttpId(), responseCode, finalResponseString);
                    }
                    if (!consumed) {
                        //统一处理错误请求
//                        TJUtils.showToast("http " + request.getHttpId() + " " + finalResponseString);
                    }
                }
            }
        });

    }
}
